package com.cms.recursoshumanos.ui.ocio;

import com.cms.recursoshumanos.cache.ListaOcioCache;
import com.cms.recursoshumanos.cache.UserInfoCache;
import com.cms.recursoshumanos.component.OcioListButtonField;
import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.container.ForegroundManager;
import com.cms.recursoshumanos.container.ListStyleButtonSetScrollManager;
import com.cms.recursoshumanos.container.SearchBarManager;
import com.cms.recursoshumanos.container.TwoColumnFieldManager;
import com.cms.recursoshumanos.engine.ScreenEngine;
import com.cms.recursoshumanos.handler.ListaOcioScreenHandler;
import com.cms.recursoshumanos.object.Ocio;
import com.cms.recursoshumanos.object.list.ListaOcio;
import com.cms.recursoshumanos.popup.ShowDialogAlert;
//import com.cms.recursoshumanos.utilities.Utileria;





import com.cms.recursoshumanos.ui.RecursosHumanosScreen;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BorderFactory;

public class ListaOcioScreen extends RecursosHumanosScreen implements FieldChangeListener 
{

	private static ListaOcioScreen instance = null;
	private ListaOcio lista_ocio;
	
	//private Utileria tools = new Utileria();
	
	SearchBarManager sbm;
	ListStyleButtonSetScrollManager buttonSet;
	VerticalFieldManager vfm;
	//TwoColumnFieldManager twoColumnManager;
	
	LabelField lblNombre,lblCantidadElemento;

	public static ListaOcioScreen getInstance(ListaOcio lista_ocio)
	{
		if(instance == null)
    	{
    		instance = new ListaOcioScreen(lista_ocio);
    	}
		else
		{
			instance.lista_ocio = lista_ocio;
			instance.reset();
		}
    	return instance;
    }
	
	
    private ForegroundManager _foreground;    
    
	public ListaOcioScreen(ListaOcio lista_ocio) 
	{
		super( NO_VERTICAL_SCROLL | USE_ALL_HEIGHT );
		
		this.lista_ocio = lista_ocio;
		
		setComponents();
	}
			
	
	protected void makeMenu(Menu menu, int instance) 
	{
		MenuItem refreshButton = new MenuItem("Actualizar", 0, 0) 
        {
			public void run() 
			{
				ListaOcioScreenHandler handler = new ListaOcioScreenHandler();
	   			handler.refreshListadoOcio(UserInfoCache.getInstance().getUsuario().getNombre_Usuario(), 
	   					UserInfoCache.getInstance().getUsuario().getPassword());
			}
		};
		menu.add(refreshButton);
		super.makeMenu(menu, instance);
	}

	public void setVFMLista()
	{
		
		lblCantidadElemento = new LabelField("Se encontro "+lista_ocio.cantElementListaOcio()+
				" registro(s).", 
				DrawStyle.HCENTER | Field.FIELD_HCENTER);
		lblCantidadElemento.setFont(font_italic_7);
		
		Field separator = new SeparatorField();
        separator.setMargin( 2, 0, 2, 0 );
        vfm.add(lblCantidadElemento);
        vfm.add(separator);
        
        
	}
	public void reset() 
	{
		vfm.deleteAll();
		this.setVFMLista();
		try 
		{
			if(buttonSet.getFieldCount() > 0) 
			{
				//sbm.setFocus();
				buttonSet.deleteAll();
			}
		} 
		catch (Exception e) 
		{
			ShowDialogAlert alert = new ShowDialogAlert("Exception in delete fields...");
			alert.run();
		}
		showListField();;
		//pis = Json.getInstance().getPIs();
	}
	
	public void setComponents() 
	{
		setTitle("Lista de Alt. de Distraccion");
		vfm = new VerticalFieldManager( Field.FIELD_HCENTER | VerticalFieldManager.NON_FOCUSABLE  );
		_foreground = new ForegroundManager(NO_VERTICAL_SCROLL);
		
		/*twoColumnManager = new TwoColumnFieldManager( Display.getWidth() / 2, USE_ALL_WIDTH | FIELD_HCENTER | DrawStyle.HCENTER );
        twoColumnManager.setBorder( BorderFactory.createBitmapBorder( new XYEdges( 10, 10, 10, 10 ), Bitmap.getBitmapResource( "border_simple_white.png" ) ) );
        twoColumnManager.setMargin( 6, 6, 6, 6 );
        twoColumnManager.setPadding( 2, 2, 2, 2 );*/
		
        buttonSet = new ListStyleButtonSetScrollManager();
        buttonSet.setScreen(this);
        
        this.setVFMLista();
        sbm = new SearchBarManager(SearchBarManager.STRING_FILTER)
		{
			protected boolean keyChar(char ch, int status, int time) 
			{
				switch (ch) 
			    {
			        case Characters.BACKSPACE:
			        	if (sbm.getSearchText().length() != 0)
			        	{
			        		String texto = sbm.getSearchText().substring(0, sbm.getSearchText().length() - 1);
			        		if (texto.length() == 0)
			        		{
			        			setListadoCompleto();
			        		}
			        		else
			        		{
			        			setListadoParam(texto);
			        		}
			        		//setListadoParam(texto);
			        	}
			        	return super.keyChar(ch, status, time);
			        case Characters.ENTER:

			            
			            return true;
			        
			        default:
			        	
			        	setListadoParam(sbm.getSearchText()+ch);
			        	
			        	return super.keyChar(ch, status, time);

			    }
				
			}
		};
		showListField();

        /*twoColumnManager.add(sbm);
		twoColumnManager.add(vfm);
		twoColumnManager.add(buttonSet);
		
        _foreground.add( twoColumnManager );*/
		_foreground.add(sbm);
		_foreground.add(vfm);
		_foreground.add(buttonSet);
		
        add( _foreground );
	}
	public void setListadoCompleto()
	{
		lista_ocio = ListaOcioCache.getInstance().getListaOcio();
		this.reset();
		//twoColumnManager.invalidate();
		_foreground.invalidate();
	}
	public void setListadoParam(String buscador)
	{
		int textlength = buscador.length();
		ListaOcio aux_listado_ocio = ListaOcioCache.getInstance().getListaOcio();
		ListaOcio listado_ocio_mostrar = new ListaOcio();
		for (int i = 0; i < aux_listado_ocio.cantElementListaOcio(); i++) 
		{
			Ocio ocio_aux = aux_listado_ocio.getOcioAtIndex(i);
	   
			String nombre_ocio = ""+ocio_aux.getNombreEstablecimientoOcio();
	   
			if (textlength <= nombre_ocio.length()) 
			{
				if (buscador.equalsIgnoreCase((String) nombre_ocio.substring(0,textlength))) 
				{
					listado_ocio_mostrar.addOcio(ocio_aux);
				}
			}
		}
		lista_ocio = listado_ocio_mostrar;
		this.reset();
		//twoColumnManager.invalidate();
		_foreground.invalidate();
	}
	public void showListField()
	{
		buttonSet.deleteAll();
		OcioListButtonField link;
		
		for(int i = 0; i < lista_ocio.cantElementListaOcio() ; i++) 
		{

			link = new OcioListButtonField(lista_ocio.getOcioAtIndex(i), LabelField.ELLIPSIS) 
			{
			
				protected void paintBackground( Graphics g )
				{
					  COLOR_BACKGROUND_FOCUS = Constant.COLOR_LIST_FOCUS;
					  COLOR_BACKGROUND_FOCUS_ACTION = Constant.COLOR_FOCUS_NORMAL;

				      if( _drawPosition < 0 ) 
				      {
				          // it's like a list field, let the default background be drawn
				          super.paintBackground( g );
				          return;
				      }
				      
				      int oldColour = g.getColor();
				      
				      int focus = COLOR_BACKGROUND_FOCUS;
				      if(_doAction) 
				    	  focus = COLOR_BACKGROUND_FOCUS_ACTION;
				      
				      int background = g.isDrawingStyleSet( Graphics.DRAWSTYLE_FOCUS ) ? focus : Constant.COLOR_BACKGROUND;
				      try 
				      {
				          if( _drawPosition == 0 ) 
				          {
				              // Top
				              g.setColor( background );
				              g.fillRoundRect( 0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.drawLine( 0, getHeight() - 1, getWidth(), getHeight() - 1 );
				          } 
				          else if( _drawPosition == 1 ) 
				          {
				              // Bottom 
				              g.setColor( background );
				              g.fillRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				          } 
				          else if( _drawPosition == 2 ) 
				          {
				              // Middle
				              g.setColor( background );
				              g.fillRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.drawLine( 0, getHeight() - 1, getWidth(), getHeight() - 1 );
				          } 
				          else 
				          {
				              // Single
				              g.setColor( background );
				              g.fillRoundRect( 0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS );
				          }
				      } 
				      finally 
				      {
				          g.setColor( oldColour );
				      }
				}
			};

			link.setChangeListener( this );
			buttonSet.add( link );
		}
		/*if(from == 0 && pis.size() >= 1) 
		{
//			if(from == 0 && pis.size() < Integer.parseInt(BaseFacade.NUM_ITEMS)) {
//				
//			} else {
//				buttonSet.add(new LoadingListStyleButtonField(loadingImage));
//			}
			buttonSet.setFocus();
		}*/
	}
	public void fieldChanged( Field field, int context ) 
	{
		ScreenEngine.getInstance().goEstablecimientoPopUp(this.lista_ocio.getOcioAtIndex(field.getIndex()));
	}	
}



